const api = require('../../../api/mop_api');
import { toast, log, err, back } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    scope: '',
    type: '',
    ratio: '',
    payAmount: '',
    points: '',
    startTime: '',
    endTime: '',
    id: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const id = options.id;
    if (id) {
      this.setData({ id });
      try {
        const res = await api.payhdGet({ id });
        if (res.respCode === 200) {
          const item = JSON.parse(res.source);
          log(item);
          const { title, scope, type, ratio, payAmount, points, startTime, endTime } = item;
          this.setData({
            title,
            scope,
            type,
            ratio,
            payAmount,
            points,
            startTime,
            endTime,
          });
        } else {
          toast(res.msg);
        }
      } catch (error) {
        err(error);
        throw error;
      }
    }
  },
  async paypost() {
    try {
      const { title, scope, type, ratio, payAmount, points, startTime, endTime } = this.data;
      const coverUrl = '';
      const data = {
        title,
        scope,
        type,
        ratio: type === 'RATIO' ? ratio : undefined,
        payAmount: type !== 'RATIO' ? payAmount : undefined,
        points: type !== 'RATIO' ? points : undefined,
        startTime,
        endTime,
        coverUrl,
        status: 'NORMAL',
      };
      const res = await api.payhdpost(data);
      if (res.respCode === 200) {
        toast('添加成功');
        back();
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async putpost() {
    try {
      const { title, scope, type, ratio, payAmount, points, startTime, endTime, id } = this.data;
      const coverUrl = '';
      const data = {
        title,
        scope,
        type,
        ratio: type === 'RATIO' ? ratio : undefined,
        payAmount: type !== 'RATIO' ? payAmount : undefined,
        points: type !== 'RATIO' ? points : undefined,
        startTime,
        endTime,
        coverUrl,
        id,
      };
      const res = await api.payhdput(data);
      if (res.respCode === 200) {
        toast('修改成功');
        back();
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
    }
  },
  onscope(e) {
    this.setData({ scope: e.detail });
  },
  ontype(e) {
    this.setData({ type: e.detail });
  },
  start(e) {
    this.setData({ startTime: e.detail.value });
  },
  end(e) {
    this.setData({ endTime: e.detail.value });
  },
});
